
//
//  ScanViewController.m
//  PersonalManager
//
//  Created by user on 16/8/15.
//  Copyright © 2016年 Haiyun.Qian. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ScanView.h"

@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>

/** 存储上一个界面推过来的识别扫描类型的字符串 */
@property(nonatomic,strong) NSString *codeTypeString;

/*
 AVCaptureSession 管理输入(AVCaptureInput)和输出(AVCaptureOutput)流，包含开启和停止会话方法。
 AVCaptureDeviceInput 是AVCaptureInput的子类,可以作为输入捕获会话，用AVCaptureDevice实例初始化。
 AVCaptureDevice 代表了物理捕获设备如:摄像机。用于配置等底层硬件设置相机的自动对焦模式。
 AVCaptureMetadataOutput 是AVCaptureOutput的子类，处理输出捕获会话。捕获的对象传递给一个委托实现AVCaptureMetadataOutputObjectsDelegate协议。协议方法在指定的派发队列（dispatch queue）上执行。
 AVCaptureVideoPreviewLayerCALayer的一个子类，显示捕获到的相机输出流。
 */

@property(nonatomic,strong) AVCaptureDevice *captureDevice;//设备
@property(nonatomic,strong) AVCaptureSession *captureSession;//会话
@property(nonatomic,strong) AVCaptureVideoPreviewLayer *previewlayer;//放置会话的层
@property(nonatomic,strong) AVCaptureDeviceInput *captureInput;//输入流
@property(nonatomic,strong) AVCaptureMetadataOutput *captureOuput;//输出流

@property(nonatomic,strong) ScanView *scanView;

@end

@implementation ScanViewController

/** 懒加载,设备,会话,预览层,输入流,输出流 */
- (AVCaptureDevice *)captureDevice {
    if (!_captureDevice) {
        //创建设备(手机摄像头)
        _captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _captureDevice;
}
- (AVCaptureSession *)captureSession {
    if (!_captureSession) {
        //创建会话
        _captureSession = [AVCaptureSession new];
        _captureSession.sessionPreset = AVCaptureSessionPresetHigh;
    }
    return _captureSession;
}
- (AVCaptureDeviceInput *)captureInput {
    if (!_captureInput) {
        _captureInput = [AVCaptureDeviceInput deviceInputWithDevice:self.captureDevice error:nil];
    }
    return _captureInput;
}
- (AVCaptureMetadataOutput *)captureOuput {
    if (!_captureOuput) {
        _captureOuput = [AVCaptureMetadataOutput new];
        [_captureOuput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    }
    return _captureOuput;
}
- (AVCaptureVideoPreviewLayer *)previewlayer {
    if (!_previewlayer) {
        _previewlayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
        _previewlayer.videoGravity = AVLayerVideoGravityResize;
        _previewlayer.frame = self.view.bounds;
    }
    return _previewlayer;
}
- (ScanView *)scanView {
    if (!_scanView) {
        _scanView = [[ScanView alloc] initWithFrame:self.view.bounds];
        _scanView.backgroundColor = [UIColor clearColor];
    }
    return _scanView;
}
/* 懒加载到此结束 */

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"扫一扫";
    self.view.backgroundColor = [UIColor blackColor];
}

/** 自定义带有扫码类型的初始化方法 */
- (instancetype)initWithString:(NSString *)string {
    if (self = [super init]) {
        self.codeTypeString = string;
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self startReading];
    [self.view addSubview:self.scanView];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self stopReading];
}

//开始读取
- (void)startReading {
    if ([self.captureSession canAddInput:self.captureInput]) {
        [self.captureSession addInput:self.captureInput];
    }
    if ([self.captureSession canAddOutput:self.captureOuput]) {
        [self.captureSession addOutput:self.captureOuput];
    }
    
    if ([self.codeTypeString isEqualToString:@"qrCode"]) {
        self.captureOuput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    }else{
        self.captureOuput.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,
                                                  AVMetadataObjectTypeEAN8Code,
                                                  AVMetadataObjectTypeCode128Code,
                                                  AVMetadataObjectTypeQRCode
                                                  ];
    }
    
    [self.view.layer insertSublayer:self.previewlayer atIndex:0];
    
    //设置有效扫描区域
    CGRect rectAble = self.scanView.blankArea;
    //修正扫描区域
    CGFloat screenHeight = self.view.frame.size.height;
    CGFloat screenWidth = self.view.frame.size.width;
    
    [self.captureOuput setRectOfInterest:CGRectMake(rectAble.origin.y / screenHeight,
                                                    rectAble.origin.x / screenWidth,
                                                    rectAble.size.height / screenHeight,
                                                    rectAble.size.width / screenWidth)];
    
    [self.captureSession startRunning];
}

//停止读取
- (void)stopReading {
    [self.captureSession stopRunning];
    self.captureSession = nil;
    [self.previewlayer removeFromSuperlayer];
    [self.scanView.timer invalidate];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *readableObject = [metadataObjects lastObject];
        [self stopReading];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"scanResult" object:nil userInfo:@{@"result":readableObject.stringValue}];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
